package com.sanji.sjmallmodule.phoneshell;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.sanji.sjmallapp.MallApplication;
import com.sanji.sjmallapp.R;
import com.sanji.sjmallconfig.ConfigAPI;
import com.sanji.sjmallconfig.ConfigConts;
import com.sanji.sjmallmanager.http.NoHttpCallBack;
import com.sanji.sjmallmanager.http.NoHttpListener;
import com.sanji.sjmallmodule.goods.BaseFrament;
import com.sanji.sjmallutils.SharePreferenceUtil;
import com.sanji.sjmallutils.Tools;
import com.sanji.sjmallwidget.XListView;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONArray;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 定制订单--页签
 * Created by Administrator on 2017/9/16.
 */

public class ShellOrderFragment extends BaseFrament implements XListView.IXListViewListener,NoHttpListener,ShellOrderAdapter.OrderListener {

    @BindView(R.id.shell_order_viewpager_listview)XListView mMyOrderViewpagerListview;
    private int pageIndex = 0;
    //是否重置
    private boolean isRedo = false;

    //标志位 标志已经初始化完成
    private boolean isPrepared;
    private SharePreferenceUtil sp;
    private String uid;
    private String status;
    private int page = 0;//页数
    private int size = 10;
    private boolean refresh = false;
    private boolean pagerCanloder = false;
    private List<ShellCartBean> orderList = new ArrayList<>();

    private ShellOrderAdapter shellOrderAdapter;

    private String orderUrl = "";
    private int editKKMovePos;
    private String orderRdUrl = "";
    //重做
    private String rdKmoveId = "";


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.viewpager_shell_order, null);
        ButterKnife.bind(this, view);
        isPrepared = true;
        initView();
        lazyLoadData();
        return view;
    }

    private void initView(){
        sp = MallApplication.getApplication().myShare;
        uid = sp.getString(ConfigConts.USER_ID, null);
        mMyOrderViewpagerListview.setPullLoadEnable(false);
        mMyOrderViewpagerListview.setHeaderDividersEnabled(false);
        mMyOrderViewpagerListview.setFooterDividersEnabled(false);
        mMyOrderViewpagerListview.setXListViewListener(this);


    }

    @Override
    public void lazyLoadData() {
        if (!isPrepared || !isVisible) {
            return;
        }
        pageIndex = this.getArguments().getInt("pages");
        if (pageIndex == 1){
            isRedo = true;
        }else{
            isRedo = false;
        }
        status = this.getArguments().getString("status");
        boolean refres = MallApplication.getApplication().getShellRefreshMap().get(pageIndex);
        if (orderList.size() == 0) {
            //未支付网络请求
            requestOrder();
        } else if (refres) {
            onRefresh();
            MallApplication.getApplication().getShellRefreshMap().put(pageIndex, false);
        } else {
            shellOrderAdapter.notify(orderList);
        }

    }

    @Override
    public void onRefresh() {
        //刷新
        refresh = true;
        page = 0;
        requestOrder();
    }

    @Override
    public void onLoadMore() {
        //加载更多
        if (pagerCanloder) {
            page++;
            requestOrder();
        }
    }

    private void requestOrder(){
        orderUrl = ConfigAPI.PHONE_SHELL_ORDER_LIST + "page=" + page + "&size=" + size;
        if (!"".equals(status)){
            orderUrl = orderUrl + "&status=" + URLEncoder.encode(status);
        }
//        orderUrl = URLEncoder.encode(orderUrl);
        Request<JSONObject> orderRequest = NoHttp.createJsonObjectRequest(orderUrl, RequestMethod.GET);
        orderRequest.addHeader("X-Authorization-MemberId",uid);
        orderRequest.setCancelSign(orderUrl.hashCode());
        NoHttpCallBack.getInstance().add(getActivity(), orderUrl.hashCode(), orderRequest, this, true, true);
//        try {
//            JSONObject json = new JSONObject();
//            json.put("page",page);
//            json.put("size",size);
//            if (!"".equals(status)){
//                json.put("status",status);
//            }
//            orderRequest.setDefineRequestBodyForJson(json);
//
//        }catch (Exception e){
//            e.printStackTrace();
//        }
    }

    @Override
    public void onSuccessed(int what, Response response) {
        if (what == orderUrl.hashCode()){
            JSONObject jsonObject = (JSONObject) response.get();
            JSONArray content = jsonObject.optJSONArray("content");
            if (content!=null && content.length()>0){
                //有数据
                int totalPages = jsonObject.optInt("totalElements");
                if (totalPages-1 > page) {
                    pagerCanloder = true;
                } else {
                    pagerCanloder = false;
                }
                mMyOrderViewpagerListview.setPullLoadEnable(pagerCanloder);

                if (refresh) {
                    orderList.clear();
                    refresh = false;
                }

                int length = content.length();
                ShellCartBean cart = null;
                JSONObject obj = null;
                JSONObject order = null;
                for (int i=0;i<length;i++){
                    obj = content.optJSONObject(i);
                    cart = new ShellCartBean();
                    cart.setCategoryName(obj.optString("categoryName"));
                    cart.setTitle(obj.optString("title"));
                    cart.setKkmoveUrl(obj.optString("kkmoveUrl"));
                    cart.setShowView(obj.optString("showView"));
                    order = obj.optJSONObject("order");
                    cart.setId(order.optString("id"));
                    cart.setKkmoveId(order.optString("kkmoveId"));
                    cart.setQuantity(order.optInt("quantity"));
                    cart.setGoodsId(order.optString("goodsId"));
                    cart.setPrice(order.optDouble("price"));
                    cart.setSalePrice(order.optDouble("salePrice"));
                    cart.setRetailPrice(order.optDouble("retailPrice"));
                    cart.setUsername(order.optString("username"));
                    cart.setUserMobile(order.optString("userMobile"));
                    cart.setStatus(order.optString("status"));
                    cart.setAmount(order.optDouble("amount"));
                    cart.setOrderNum(order.optString("orderNum"));
                    cart.setCreateTime(order.optString("createTime"));
                    cart.setCarriage(order.optInt("carriage"));
                    cart.setGyResult(order.optString("gyResult"));
                    cart.setMemberId(order.optString("memberId"));
                    cart.setSignForTime(order.optString("signForTime"));
                    cart.setPayNum(order.optString("payNum"));
                    orderList.add(cart);
                }

                if (shellOrderAdapter == null){
                    shellOrderAdapter = new ShellOrderAdapter(getActivity(),orderList,isRedo);
                    shellOrderAdapter.setOrderListener(this);
                    mMyOrderViewpagerListview.setAdapter(shellOrderAdapter);
                }else{
                    shellOrderAdapter.notify(orderList);
                }
                mMyOrderViewpagerListview.stopRefresh();
                mMyOrderViewpagerListview.stopLoadMore();


            }
        }else if(what == orderRdUrl.hashCode()){
            JSONObject jsonObject = (JSONObject) response.get();
            String status = jsonObject.optString("status");
            if (ConfigConts.STATUS_SUCCESS.equals(status)){
                Tools.toastTools(getActivity(),"修改成功");

                ShellCartBean cart = orderList.get(editKKMovePos);
                String oldKmId = cart.getKkmoveId();
                cart.setKkmoveId(rdKmoveId);
                String showUrl = "http://www.kkmove.com/appadmin/designview/" + rdKmoveId;
                cart.setShowView(showUrl);
                String kkmoveUrl = cart.getKkmoveUrl();
                kkmoveUrl = kkmoveUrl.replace(oldKmId,rdKmoveId);
                cart.setKkmoveUrl(kkmoveUrl);
                //刷新adapter中item
                shellOrderAdapter.updateItemView(mMyOrderViewpagerListview,editKKMovePos,showUrl);

            }else{
                Tools.toastTools(getActivity(),"修改失败");
            }
        }
    }

    @Override
    public void onFailed(int what, Response response) {
        Tools.toastTools(getActivity(), getResources().getString(R.string.request_time_out));
    }

    @Override
    public void kkmoveRedo(int pos) {
        editKKMovePos = pos;
        ShellCartBean cart = orderList.get(pos);

        Intent intent = new Intent(getActivity(),ShellWebViewActivity.class);
        intent.putExtra("webType",1);
        intent.putExtra("kkmoveUrl",cart.getKkmoveUrl());
        startActivityForResult(intent,ConfigConts.ACTION_SHELL_CART_EDIT);
    }

    @Override
    public void itemClick(int pos) {
        if (orderList.size()>0){
            ShellCartBean bean = orderList.get(pos);
            Intent intent = new Intent(getActivity(),ShellOrderDetailActivity.class);
            intent.putExtra("orderNum",bean.getOrderNum());
            intent.putExtra("showView",bean.getShowView());
            startActivity(intent);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK){
            switch (requestCode){
                case ConfigConts.ACTION_SHELL_CART_EDIT:
                    rdKmoveId = data.getStringExtra("kkmoveId");
//                    String showUrl = "http://www.kkmove.com/appadmin/designview/" + rdKmoveId;

                    //订单重做
                    orderRedo();
                    break;
            }
        }
    }

    private void orderRedo(){
        String orderNum = orderList.get(editKKMovePos).getOrderNum();
        orderRdUrl = ConfigAPI.PHONE_SHELL_ORDER_REDO + orderNum + "&kkmoveId="+rdKmoveId;
        Request<JSONObject> rdRequest = NoHttp.createJsonObjectRequest(orderRdUrl, RequestMethod.POST);
        rdRequest.setCancelSign(orderRdUrl.hashCode());
        NoHttpCallBack.getInstance().add(getActivity(), orderRdUrl.hashCode(), rdRequest, this, true, true);

    }
}
